package com.xinyues.gamemanager.security;

import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import com.xinyues.gamemanager.dao.entity.GmAccount;
import com.xinyues.gamemanager.service.GmAccountService;
public class GmAuthenticationManager implements AuthenticationManager{
    private Logger logger = LoggerFactory.getLogger(GmAuthenticationManager.class);
    private GmAccountService accountService;
    public GmAuthenticationManager(GmAccountService accountService) {
        this.accountService = accountService;
    }
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        if(authentication.getPrincipal() == null || authentication.getCredentials() == null) {
            throw new BadCredentialsException("登陆验证失败,用户名或密码为空");
        }
        String username = (String)authentication.getPrincipal();
        //从数据库获取账户信息
        GmAccount gmAccount = accountService.getGmAccount(username);
        if(gmAccount == null) {
            throw new BadCredentialsException("账户不存在，username:" + username);
        }
        String password = (String)authentication.getCredentials();
        if(!gmAccount.getPassword().equals(password)) {
            throw new BadCredentialsException("用户或密码错误");
        }
        logger.info("{} 登陆成功",username);
        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();//这里添加权限
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(authentication.getPrincipal(), authentication.getCredentials(), grantedAuthorities);
        authenticationToken.setDetails(gmAccount);
        
        return authenticationToken;
    }
}
